package com.fantasy.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * @author heqichang
 * 服务端
 * */
public class ThreadSocketServer extends Thread {

	Socket server;
	
	//保存服务端的姓名
	static String name = new String();

	public void run() {
		try {
			
			//启动一个线程来接收客户端信息
			ThreadServer thread = new ThreadServer(server);
			thread.start();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			PrintWriter pw = new PrintWriter(server.getOutputStream());
			
			//第一次发送自己的姓名给客户端
			pw.println(name);
			
			//循环发送信息给客户端
			while (true) {
				String s = br.readLine();
				pw.println(s);
				pw.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public ThreadSocketServer(Socket s) {
		this.server = s;
	}

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		
		//绑定服务端在9999端口
		ServerSocket server = null;
		try {
			server = new ServerSocket(9999);
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		Socket socket = null;

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("请输入您的姓名：>");
		try {
			name = br.readLine();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		while (true) {
			//监听客户端程序
			try {
				socket = server.accept();
				//一个客户端连接后启动一个线程进行处理
				ThreadSocketServer thread = new ThreadSocketServer(socket);
				thread.start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
				
		}
	}
}
